package com.supplychain.scm.core.rocketmq.storage;

import cn.hutool.core.util.IdUtil;
import com.supplychain.scm.core.rocketmq.bean.BaseMqMessage;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.Executor;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName IMqMessageStorage
 * @Description Mq发送消息存储接口
 * @createTime 09:20:00 2022/12/05
 */
public interface IMqMessageStorage{

    /**
     * Mq存储方法
     * @param baseMqMessage
     * @return
     */
    boolean createMqMessageStorage(BaseMqMessage baseMqMessage);

    /**
     * 存储message数据修改
     * @param baseMqMessage
     * @return
     */
    boolean updateMqMessageByUniqueKey(BaseMqMessage baseMqMessage);

    default BaseMqMessage updateMessage(BaseMqMessage message, Executor executor) {
        Boolean ifStore = Optional.ofNullable(message).map(BaseMqMessage::getIfStore).orElse(Boolean.TRUE);
        if(ifStore) {
            if (Objects.nonNull(message.getNotSave()) && message.getNotSave()) {
                return null;
            }
            if(Objects.nonNull(executor)) {
                executor.execute(()-> updateMqMessageByUniqueKey(message));
            } else{
                updateMqMessageByUniqueKey(message);
            }
        }
        return message;
    }
    /**
     * 消息保存
     * @param message message
     * @param executor executor
     */
    @SneakyThrows
    default BaseMqMessage saveMessage(BaseMqMessage message, Executor executor){
        Boolean ifStore = Optional.ofNullable(message).map(BaseMqMessage::getIfStore).orElse(Boolean.TRUE);
        if(ifStore) {
            if (Objects.nonNull(message.getNotSave()) && message.getNotSave()) {
                return null;
            }
            if(StringUtils.isBlank(message.getUniqueKey())) {
                message.setUniqueKey(String.valueOf(IdUtil.getSnowflakeNextId()));
            }
            if(StringUtils.isBlank(message.getMessageLinkId())) {
                message.setMessageLinkId(message.getUniqueKey());
            }
            if(Objects.nonNull(executor)) {
                executor.execute(()-> createMqMessageStorage(message));
            } else{
                createMqMessageStorage(message);
            }
        }
        return message;
    }
}
